package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.ExamMapper;
import com.entrogy.dao.UserMapper;
import com.entrogy.service.ExamService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author 罗兴江
 * @date 2019/5/31 0024 下午 3:42
 * 考试管理 service接口实现类
 */
@Service(value="examService")
@Transactional
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<ExamEntity> findExamList(String userId, Integer schoolCode, Integer examId) {
        return examMapper.findExamList(userId, schoolCode, examId);
    }

    @Override
    public Integer addExam(ExamEntity examEntity) {
        // 首先判断这个考试能不能够创建，即判断要考的所有班级是否已分配所有的要考的所有科目
        List<Integer> classIds = examEntity.getClassIds();
        List<Integer> staticCourseIds = examEntity.getCourseIds();
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        for (Integer classId : classIds) {
            // 查询某个班级拥有的所有静态科目
            List<Integer> classStaticCourseIds = examMapper.listClassStaticCourse(classId, schoolCode);
            // 如果要考试的科目数量大于这个班已分配的科目数量的话，那么肯定不能创建考试
            if (staticCourseIds.size() > classStaticCourseIds.size()){
                return null;
            }
            for (Integer staticCourseId : staticCourseIds) {
                // 如果这个班级拥有的所有静态科目不包含某一科要考试的静态科目的话，那么不能创建考试
                if (!classStaticCourseIds.contains(staticCourseId)){
                    return null;
                }
            }
        }

        //首先在考试记录表内插入考试记录并且获取自增id的值
        int row = examMapper.addExam(examEntity);
        //向考试-科目表中插入数据,使用静态id将课程id找出，不加学生id的限制
        int examId = examEntity.getExamId();
        List<Integer> courseIds1 = examMapper.findClassExamCourseIdsByStaticCourseIds(schoolCode,examEntity.getCourseIds(),examEntity.getGradeId(),examEntity.getClassIds());
        int row1 = examMapper.addExamCourse(examId,courseIds1);
        //向考试-班级表中插入数据
        int row2 = examMapper.addExamClass(examId,classIds);
        String scoreTableName = findScoreTableNameByExamId(examId);
        //向考试-分数表中插入数据，即向考试-成绩表中加入每个学生该次考试每个科目的初始成绩
        //查找出此次要考试的学生id的集合
        List<Integer> studentIds = examMapper.findExamStuIdsByClassId(schoolCode, classIds, examId);
        // 根据学生和考试id查询出他此次考试的科目id集合,因为前端会传输statice_course_id的集合过来，
        // 根据固定的statcie_course_id和course_information来对应找到一个静态课程（即只表示课程，与班级无关），
        // 再通过course_information再找到该静态课程对应哪些班级的课程
        for (int i = 0; i < studentIds.size(); i++) {
            List<Integer> courseIds;
            //根据要考的静态课程以及要考的班级可以得到要考的具体的课程。然后插入考试表内
            List<CourseEntity> courseList = examMapper.findStuExamCourseIdsByStaticCourseIds(schoolCode, staticCourseIds, studentIds.get(i), examEntity.getClassIds());
            int result = examMapper.insertInitExamScore(examId,scoreTableName,studentIds.get(i),courseList);
            if(result != courseList.size()){
                throw new RuntimeException("初始化成绩失败");
            }
        }
        //初始化该次考试的排名记录
        Integer row3 = examMapper.insertInitExamRank(studentIds, examId);
        //插入记录的结果
        if (row == 1 && row1 == courseIds1.size() && row2 == examEntity.getClassIds().size() && row3 == studentIds.size()){
            return examEntity.getExamId();
        }else {
            throw new RuntimeException("考试创建失败");
        }
    }

    @Override
    public List<SimpleExamEntity> findSimpleExamList(Integer gradeId, String teacherId, Integer schoolCode) {
        return examMapper.findSimpleExamList(gradeId,teacherId,schoolCode);
    }

    @Override
    public List<GradeEntity> findExamGradeByClassIds(List<Integer> examClassIds, Integer examId) {
        return examMapper.findExamGradeByClassIds(examClassIds, examId);
    }

    @Override
    public String findScoreTableNameByExamId(Integer examId){
        return examMapper.findScoreTableNameByExamId(examId);
    }

    @Override
    public List<SimpleExamEntity> findExamListByStuId(Integer stuId) {
        return examMapper.findExamListByStuId(stuId);
    }

    @Override
    public List<SimpleExamEntity> findSimpleExamListByGradeIdOrUid(String gradeId, String uId, Integer schoolCode) {
        return examMapper.findSimpleExamListByGradeIdOrUid(gradeId, uId, schoolCode);
    }

    @Override
    public List<Integer> listExamClassId(Integer examId) {
        return examMapper.listExamClassId(examId);
    }

    @Override
    public List<SimpleExamEntity> listSchoolExam(Integer schoolCode, String examName, String examTime) {
        return examMapper.listSchoolExam(schoolCode, examName, examTime);
    }

    @Override
    public boolean deleteExam(Integer examId) {
        return examMapper.deleteExam(examId) == 1;
    }

    @Override
    public List<SimpleExamEntity> listExamForCourseTeacher(String teacherId) {
        return examMapper.listExamForCourseTeacher(teacherId);
    }

    @Override
    public int countExam(Integer schoolCode) {
        return examMapper.countExam(schoolCode);
    }

    @Override
    public Integer countExamStudent(Integer examId) {
        return examMapper.countExamStudent(examId);
    }

    @Override
    public List<ClassEntity> listExamClass(Integer examId) {
        return examMapper.listExamClass(examId);
    }

    @Override
    public List<SimpleExamEntity> listExamForParent(String uId, String examName, String examTime) {
        return examMapper.listExamForParent(uId, examName, examTime);
    }

    @Override
    public List<CourseEntity> listExamCourse(Integer examId) {
        return examMapper.listExamCourse(examId);
    }

    @Override
    public boolean insertRankGenerateRecord(Integer examId, Integer requireCourseClassRank, Integer requireCourseGradeRank, Integer requireTotalScoreClassRank, Integer requireTotalScoreGradeRank, Integer requireScienceOrArtsClassRank, Integer requireScienceOrArtsGradeRank, Integer requireClassAvgScore, Integer requireGradeAvgScore) {
        return examMapper.insertRankGenerateRecord(examId, requireCourseClassRank, requireCourseGradeRank, requireTotalScoreClassRank, requireTotalScoreGradeRank, requireScienceOrArtsClassRank, requireScienceOrArtsGradeRank, requireClassAvgScore, requireGradeAvgScore);
    }

    @Override
    public int deleteRankGenerateRecord(Integer examId) {
        return examMapper.deleteRankGenerateRecord(examId);
    }

    @Override
    public JSONObject getRankGenerateRecord(Integer examId) {
        return examMapper.getRankGenerateRecord(examId);
    }

    @Override
    public boolean initExamRank(Integer examId, String scoreTableName) {
        int updateExamCourseScoreRank = examMapper.updateExamCourseScoreRank(examId, scoreTableName);
        int updateExamTotalScoreRank = examMapper.updateExamTotalScoreRank(examId, scoreTableName);
        return true;
    }

//    @Override
//    public List<SimpleExamEntity> findExamListByPosition(Integer gradeId, String teacherId, Integer schoolCode, boolean isClassLeader) {
//        List<SimpleExamEntity> simpleExamList = new ArrayList<>();
//        //gradeId不为空的话，为年级主任查看的考试
//        if (gradeId != null && StringUtils.isNoneBlank(teacherId)){
//            simpleExamList = examMapper.findExamListForGradeLeader(gradeId, schoolCode);
//        }
//        //teacherId不为空的话，为班主任或者任课老师查看考试
//        if (gradeId == null && !StringUtils.isNoneBlank(teacherId)){
//            if (isClassLeader){
//                simpleExamList = examMapper.findExamListForNormalTeacher(teacherId);
//            }else{
//                UserEntity userEntity = userMapper.getUserByUid(teacherId);
//                simpleExamList = examMapper.findExamListForClassLeader(userEntity.getClassId(), schoolCode);
//            }
//
//        }
//        return simpleExamList;
//    }


}
